class FirstPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            additem:[],
        };
    }

    componentDidMount() {
        let shopname = $.cookie('shopname'),permission = $.cookie('permission')
        this.setState({shopname,permission})
        this.freshlist()
    }

    freshlist() {
        account_getlist( res => {
            if (res.issuccess == 1) {
                let {list} = res
                list.forEach(x=>{
                    if(x.company!=null &&x.company!='' ){
                        x.username=x.phone
                    }
            })
                this.setState({list:res.list})
               
            } else {
                alert(res.msg)
            }
        })
    }





    /**新建 */
    add(e) {
        var name = prompt('请输入分类名称');
        if (name != null) {
            aoedzcate({ name }, res => {
                if (res.issuccess == '1') {
                    this.freshlist()
                } else {
                    alert(res.msg)
                }
            })
        }
    }


    // 编辑
    edit(x) {
        var name = prompt('请编辑分类名称', x.name)
        if (name != '') {
            aoedzcate({ id: x.id, name }, res => {
                if (res.issuccess == 1) {
                    this.freshlist()
                } else {
                    alert(res.msg)
                }
            })
        }

        // 
    }
    tosub(x) {
        window.location.href = "./dz_subcate.html?id=" + x.id + "&name=" + x.name;
    }
    // 排序
    toorder(id) {
        let orders = prompt("请输入1-999的正整数"), { start } = this.state
        if (orders == "" || orders == null) {
            return;
        }
        if (isNaN(orders) || orders < 1 || orders > 999) {
            return;
        }
        orders = Math.floor(orders);
        Swipersetorders({ id, orders }, res => {
            if (res.issuccess == 1) {
                //   alert("设置成功");
                this.freshlist(start);
            }
        });
    }
    // // 上架下架
    // setshow(e, i, cid) {
    //     let { start } = this.state
    //     Goodssetstate({ id: e, cid }, res => {
    //         if (res.issuccess == 1) {
    //             alert(`${i == "0" ? '下架' : '上架'}成功`)
    //             this.freshlist(start)
    //         }
    //     })
    // }
    // 删除
    del(e, cid) {
        this.setState({ delid: e, newcid: cid }, () => {
            $('#myModal').modal('toggle');
        })
    }
    confirmdel() {
        let { delid, start } = this.state
        dz_delcate(delid, res => {
            if (res.issuccess == 1) {
                // alert('删除成功')
                $('#myModal').modal('toggle');
                this.freshlist(start)
            } else {
                $('#myModal').modal('toggle');
                alert(res.msg);
            }
        })
    }

    switch(t) {
        let { type } = this.state;
        if (type != t) {
            this.setState({ type: t }, () => {
                this.freshlist()
            })
        }
    }

    clickitem(i, prop) {
        console.log({ i, prop }, 'clickitem');
        var _def = ""
        if (i > -1) _def = this.state.list[i][prop]
        var value = prompt('请填入', _def)
        if (value != null) {
            if (i < 0) {
                let { additem } = this.state;
                additem[prop] = value;
                this.setState({ additem })
            } else {
                let { list } = this.state;
                //  list[i][prop] = value
                // console.log(list,'listlist');
                // this.setState({list})
               
                dz_category_editsingle({ id: list[i].id, value, prop }, res => {
                    if (res.issuccess == 1) {
                        //   alert('修改成功')
                        this.freshlist()
                    }
                })
            }
        }
        //  this.setState({[prop]:value})

    }

    clicksditem(i, prop) {
        console.log({ i, prop }, 'clickitem');
        var _def = ""
        if (i > -1) _def = this.state.list[i][prop]
        var value = prompt('请填入', _def)
        if (value != null) {
            if (i < 0) {
                let { additem } = this.state;
                if(prop=='day'){
                    if(!(/(^[1-9]\d*$)/.test(value))){
                        alert('有效期输入有误')
                        return;
                    }
                    let ts = new Date().getTime()+1000*60*60*24*value

                 //   console.log (formatDate2(new Date(ts)),'tttsss');
                    
                    additem['deadline'] =  formatDate2(new Date(ts))
                }
                console.log(additem,'additem');
               
                additem[prop] = value;
                this.setState({ additem })
            } else {
                let { list } = this.state, item = list[i];
              
                item[prop] = value;
                item['id'] = item['buid']
                item['buid'] = $.cookie('id')
                if(prop!='name'){
                    item['name'] = item['username']
                }
                //console.log(item.name,"name123");
              //  item['shopname'] = item['name']
                if(prop=='day'){
                    if(!(/(^[1-9]\d*$)/.test(value))){
                        alert('有效期输入有误')
                        return;
                    }
                    let ts = new Date().getTime()+1000*60*60*24*value

                 //   console.log (formatDate2(new Date(ts)),'tttsss');
                    
                 item['deadline'] =  formatDate2(new Date(ts))
                 item['dl'] =  formatDate2(new Date(ts))
               
                
                }else{
                    item['dl'] =  item['deadline'].replace('T',' ')
                }
                //  list[i][prop] = value
                // console.log(list,'listlist');
                // this.setState({list})哦怕
                if(item['pwd']==''||!item['pwd'])item['pwd']=item['showpwd'] 
                console.log(item,'itemitem');
                account_aoe(item, res => {
                    if (res.issuccess == 1) {
                        //  alert('添加成功')
                        this.freshlist()
                    } else {
                        alert(res.msg)
                    }
                })
            }
        }
        //  this.setState({[prop]:value})

    }


    save(i) {
        let data = {}
        console.log(i, 'save---i');
        if (i > -1) {
            let { list } = this.state;
            data = list[i]
            data['pwd'] = data['showpwd']
        } else {
            let { additem } = this.state
            data = additem;

            // data['type'] = this.state.type 
        }
     //   if(i==-1&&!(/(^[1-9]\d*$)/.test(data.day))){
       //     alert('天数输入正整数')
     
       data['dl'] = data['deadline']
       console.log('save',data);
                    account_aoe(data, res => {
                        if (res.issuccess == 1) {
                            //  alert('添加成功')
                            this.setState({additem:{}})
                            this.freshlist()
                        } else {
                            alert(res.msg)
                        }
                    })



        console.log(data,'datadata');

    }


    upload(index) {
        if (index < 0) {
            $('#file1').click();

        } else {
            this.setState({ selectindex: index }, () => {
                $('#file').click();
            })
        }
    }

    filechangeimg(e) {
        let that = this
        var filedata = $('#file')[0].files[0];
        let _name, _fileName;
        _name = $('#file')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                let base64 = e.target.result
                //   succ&&succ( )

                uploadimg(base64, res => {
                    if (res.issuccess == 1) {
                        let {list,selectindex} = that.state,data = list[selectindex]
                      // let data = this.state.list[this.state.selectindex]
                       data['imgurl'] =res.path
                       list[selectindex] = data
                       dz_category_aoeimg(data,res=>{
                        if(res.issuccess==1){
                            that.setState({list})
                        }
                       })   
                       // that.setState({ path: res.path })
                    }
                })

            }
        }
    }
    filechangeimgnew(e) {
        let that = this
        var filedata = $('#file1')[0].files[0];
        let _name, _fileName;
        _name = $('#file1')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                uploadimg(e.target.result, res => {
                    if (res.issuccess == 1) {
                        let { additem } = that.state
                        additem['imgurl'] = res.path
                        that.setState({ additem }, () => {
                            console.log(that.state.additem, 'additem');
                        })
                    }
                })

            }
        }
    }


    selectchange(i, e) {
        console.log({ i, val: e.target.value }, 'selectchange');
        if (i > 0) {
            let { xslist } = this.state, item = xslist[i];
            item['sdtype'] = e.target.value
            aoedzcate_sd(item, res => {
                if (res.issuccess == 1) {
                    //  alert('添加成功')
                    this.freshlist()
                } else {
                    alert(res.msg)
                }
            })
        } else {
            let { addsditem } = this.state;
            addsditem['sdtype'] = e.target.value
            this.setState({ addsditem })
        }
    }

    setpassword(){
        var val = prompt('请输入密码')
        if(val!=null){
            dz_category_setpwd(md5(val + Constant.SALT),res=>{
                if(res.issuccess==1){
                    alert('设置成功')
                }
            })

        }
        
    }





    render() {
        var { list, additem, type,permission,shopname } = this.state;
        return (
            <div className="breadLinebox">
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />
                <div className='content_wrap panel-default content_wrap'>
                    <div onClick={() => { window.location.href = './dz_main.html' }} className='breadLine '>
                        <p>返回</p>

                    </div>
                    {/* <div className='inputs panel-body'>
                        <h3>首页管理</h3>
                    </div> */}
                    <div className="content form">
                        {/* <div style={{display:clicknew?"":"none"}} id="div"> */}

                        {/* <div className="tabletit" >
                            {/* <p className="delall"><img src="./src/delall.png"/>批量删除</p> 
                            <p className="add" onClick={this.add.bind(this)}>新建</p>
                        </div> */}
                        <input onChange={this.filechangeimg.bind(this)} type='file' id='file' style={{ display: "none" }} />
                        <input onChange={this.filechangeimgnew.bind(this)} type='file' id='file1' style={{ display: "none" }} />

                        <table className="tab">
                            <thead>
                                        <tr>
                                            <th style={{ 'width': '40px' }} className="tconter">序号</th>
                                            <th style={{display:permission==50?'':'none'}}  className="tconter">员工姓名</th>
                                            <th  className="tconter">账号</th>
                                            <th className="tconter">密码</th>
                                            <th className="tconter">店名</th>
                                            <th  className="tconter">有效期（天）</th>
                                            <th className="tconter">有效日期</th>
                                            <th className="cz tconter">操作</th>
                                        </tr>
                            </thead>
                            <tbody>
                                        {
                                            list.map((x, i) => {
                                                let day = new Date(x.deadline).getTime() -new Date().getTime()
                                                day = Math.ceil(day/(1000*24*60*60))
                                                return (
                                                    <tr key={i}>
                                                        {/* <td className="minwidth tconter"><img src="./src/notselection.png"/></td>  */} 
                                                        {/* <td className="tconter">{x.state=="0"?"显示":"隐藏"}</td>  */}
                                                        <td style={{ 'width': '40px' }} className="tconter">{i + 1}</td>
                                                        {/* <td style={{'width':'40px'}} className="tconter">
                                          <select value={x.sdtype} onChange={this.selectchange.bind(this,i)}>  { 
                                            [
                                                <option key={1} value={'MI'}>米 </option>,
                                                <option key={2} value={'PF'}>平方 </option>
                                            ]
                                          
                                          } </select>
                                          </td> */}
                                                        <td style={{display:permission==50?'':'none'}} onClick={this.clicksditem.bind(this, i, 'nickname')} className="tconter">{x.name}</td>
                                                        <td onClick={this.clicksditem.bind(this, i, 'name')} className="tconter">{x.username}</td>
                                                        <td onClick={this.clicksditem.bind(this, i, 'pwd')} className="tconter">{x.showpwd}</td>
                                                        <td onClick={this.clicksditem.bind(this, i, 'shopname')} className="tconter">{x.shopname}</td>
                                                        {
                                                          permission==50?  
                                                          <td  className="tconter">-</td>
                                                          :
                                                          <td onClick={this.clicksditem.bind(this, i, 'day')} className="tconter">{day}</td>
                                                        }
                                                          {
                                                          permission==50?  
                                                          <td  className="tconter">-</td>
                                                          :
                                                        <td  className="tconter">{x.deadline}</td>
                                                        }

                                                        <td className="operatebox">
                                                            <div className='operate' id={"ope" + x.id}>
                                                                {/* <p className='edit'  onClick={this.save.bind(this,i)}>保存</p> */}
                                                                <div>
                                                                    <img src="./src/del.png" />
                                                                    <p className='edit colred' onClick={this.del.bind(this, x.id)}>删除</p>
                                                                </div>
                                                            </div>

                                                        </td>
                                                    </tr>
                                                )
                                            })
                                        }

                                        {
                                            <tr>
                                                {/* <td className="minwidth tconter"><img src="./src/notselection.png"/></td>  */}
                                                {/* <td className="tconter">{x.state=="0"?"显示":"隐藏"}</td>  */}
                                                <td style={{ 'width': '40px' }} className="tconter">新建行</td>
                                                {/* <td style={{'width':'40px'}} className="tconter">
                                        <select value={additem.sdtype} onChange={this.selectchange.bind(this,-1)}>  {
                                            [
                                                <option key={1} value={'MI'}>米 </option>,
                                                <option key={2} value={'PF'}>平方 </option>
                                            ]
                                          } </select>

                                        </td> */}
                                                <td onClick={this.clicksditem.bind(this, -1, 'name')} className="tconter">{additem.name}</td>
                                                <td onClick={this.clicksditem.bind(this, -1, 'pwd')} className="tconter">{additem.pwd}</td> 
                                                <td onClick={ permission==50?"":this.clicksditem.bind(this, -1, 'shopname')} className="tconter">{permission==50?shopname:additem.shopname}</td> 
                                              
                                                {
                                                          permission==50?  
                                                          <td  className="tconter">-</td>
                                                          :
                                                <td onClick={this.clicksditem.bind(this, -1, 'day')} className="tconter">{additem.day}</td> 
                                                        }

                                                <td className="tconter">{additem.deadline||'-'}</td> 
                                                <td className="operatebox">
                                                    <div className='operate'>
                                                        <p className='edit' onClick={this.save.bind(this, -1)}>新建账号</p>
                                                    </div>
                                                </td>
                                            </tr>
                                        }
                                    </tbody>
                        </table>
                    </div>

                </div >


            </div >
        )
    }
}





ReactDOM.render(
    <div>
        {/* <LeftMenu code='0' /> */}
        <FirstPage />
    </div>
    //<Barrage/>
    , $('.container')[0]
)